﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using bts_webapp.Models;

namespace bts_webapp
{
    public partial class FlowDiagramPrint : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var stationId = this.Request.Params["stationId"];
                Init2(stationId);
            }
            catch { }
        }

        public void Init(string stationId)
        {
            var context = new Models.BTSModelDataContext();
            
            //clear all hidden fields
            this.hfStation.Value = string.Empty;
            this.hfDevices.Value = string.Empty;
            this.hfIncomingStation.Value = string.Empty;
            this.hfOutgoingStation.Value = string.Empty;
            
            var station = context.VIBA_TRAMs.FirstOrDefault(x => x.Tram_Id == stationId);
            if (station != null)
            {
                this.hfStation.Value = station.Tram_Ten;
                var devices = context.VIBA_THIET_BIs.Where(x => x.Tram_Id == stationId).ToList();
                if (devices != null && devices.Count > 0)
                {
                    bool haveIncomings = false;
                    bool haveOutgoings = false;
                    for (int i = 0; i < devices.Count; i++)
                    {
                        this.hfDevices.Value += devices[i].ThietBi_Ten + "(" + GetSoPort(devices[i].ThietBi_Id) + ")" + "|";

                        //=========== get incoming stations =================
                        {
                            var flows = context.VIBA_LUONGs.Where(x => x.Luong_Port_Den == GetSoPort(devices[i].ThietBi_Id)).ToList();
                            if (flows != null && flows.Count > 0)
                            {
                                haveIncomings = true;
                                List<string> list = new List<string>();
                                for (int j = 0; j < flows.Count; j++)
                                    list.Add(flows[j].Luong_Id_Tram_Di.Trim());
                                var inStations = context.VIBA_TRAMs.Where(x => list.Contains(x.Tram_Id.Trim())).ToList();
                                if (inStations != null && inStations.Count > 0)
                                {
                                    for (int j = 0; j < inStations.Count; j++)
                                        if (inStations[j].Tram_Id.Trim() != station.Tram_Id.Trim())
                                            this.hfIncomingStation.Value += inStations[j].Tram_Ten + "@";
                                    this.hfIncomingStation.Value = this.hfIncomingStation.Value.Trim('@') + "|";
                                }

                            }
                        }


                        //get outgoing stations
                        {
                            var flows = context.VIBA_LUONGs.Where(x => x.Luong_Port_Di == GetSoPort(devices[i].ThietBi_Id)).ToList();
                            if (flows != null && flows.Count > 0)
                            {
                                haveOutgoings = true;
                                List<string> list = new List<string>();
                                for (int j = 0; j < flows.Count; j++)
                                    list.Add(flows[j].Luong_Id_Tram_Den.Trim());
                                var outStations = context.VIBA_TRAMs.Where(x => list.Contains(x.Tram_Id.Trim())).ToList();
                                if (outStations != null && outStations.Count > 0)
                                {
                                    for (int j = 0; j < outStations.Count; j++)
                                        if (outStations[j].Tram_Id.Trim() != station.Tram_Id.Trim())
                                            this.hfOutgoingStation.Value += outStations[j].Tram_Ten + "@";
                                    this.hfOutgoingStation.Value = this.hfOutgoingStation.Value.Trim('@') + "|";
                                }

                            }
                        }

                        //process to balance
                        if (haveIncomings && !haveOutgoings)
                            this.hfOutgoingStation.Value += " |";
                        if (haveOutgoings && !haveIncomings)
                            this.hfIncomingStation.Value += " |";

                        //reset
                        haveIncomings = false;
                        haveOutgoings = false;
                    }
                    this.hfDevices.Value = this.hfDevices.Value.Trim('|');
                    this.hfIncomingStation.Value = this.hfIncomingStation.Value.Trim('|');
                    this.hfOutgoingStation.Value = this.hfOutgoingStation.Value.Trim('|');
                }


            }

            context.Dispose();

        }

        public void Init2(string stationId)
        {
            var context = new Models.BTSModelDataContext();

            //clear all hidden fields
            this.hfStation.Value = string.Empty;
            this.hfDevices.Value = string.Empty;
            this.hfIncomingStation.Value = string.Empty;
            this.hfOutgoingStation.Value = string.Empty;

            var station = context.VIBA_TRAMs.FirstOrDefault(x => x.Tram_Id == stationId);
            if (station != null)
            {
                this.hfStation.Value = station.Tram_Ten;

                var cardIdList1 = context.VIBA_LUONGs
                    .Where(x => x.Luong_Id_Tram_Di == stationId).Select(x => x.Luong_Card_Di);
                var cardIdList2 = context.VIBA_LUONGs
                    .Where(x => x.Luong_Id_Tram_Den == stationId).Select(x => x.Luong_Card_Den);
                var cardIdList = cardIdList1.Union(cardIdList2).Distinct().ToList();

                //this.NormalizeList(cardIdList);

                if (cardIdList != null && cardIdList.Count > 0)
                {
                    bool haveIncomings = false;
                    bool haveOutgoings = false;
                    for (int i = 0; i < cardIdList.Count; i++)
                    {
                        this.hfCards.Value += GetCardName(cardIdList[i].Value) + "(" + GetDeviceName(cardIdList[i].Value) + ")" + "|";

                        //=========== get incoming stations =================
                        {
                            var incomeStationIdList = context.VIBA_LUONGs
                                .Where(x => x.Luong_Id_Tram_Den == stationId && x.Luong_Card_Den == cardIdList[i].Value)
                                .Select(x => x.Luong_Id_Tram_Di).Distinct().ToList();

                            NormalizeList(incomeStationIdList);

                            if (incomeStationIdList != null && incomeStationIdList.Count > 0)
                            {
                                haveIncomings = true;

                                var inStations = this.GetStationNames(incomeStationIdList);
                                if (inStations != null && inStations.Count > 0)
                                {
                                    for (int j = 0; j < inStations.Count; j++)
                                        this.hfIncomingStation.Value += inStations[j] + "@";
                                    this.hfIncomingStation.Value = this.hfIncomingStation.Value.Trim('@') + "|";
                                }
                            }
                        }


                        //============= get outgoing stations =================
                        {
                            var outgoingStationIdList = context.VIBA_LUONGs
                                .Where(x => x.Luong_Id_Tram_Di == stationId && x.Luong_Card_Di == cardIdList[i])
                                .Select(x => x.Luong_Id_Tram_Den).Distinct().ToList();

                            NormalizeList(outgoingStationIdList);

                            if (outgoingStationIdList != null && outgoingStationIdList.Count > 0)
                            {
                                haveOutgoings = true;

                                var outStations = this.GetStationNames(outgoingStationIdList);
                                if (outStations != null && outStations.Count > 0)
                                {
                                    for (int j = 0; j < outStations.Count; j++)
                                        this.hfOutgoingStation.Value += outStations[j] + "@";
                                    this.hfOutgoingStation.Value = this.hfOutgoingStation.Value.Trim('@') + "|";
                                }
                            }
                        }

                        //process to balance
                        if (haveIncomings && !haveOutgoings)
                            this.hfOutgoingStation.Value += " |";
                        if (haveOutgoings && !haveIncomings)
                            this.hfIncomingStation.Value += " |";

                        //reset
                        haveIncomings = false;
                        haveOutgoings = false;
                    }
                    this.hfDevices.Value = this.hfDevices.Value.Trim('|');
                    this.hfCards.Value = this.hfCards.Value.Trim('|');
                    this.hfIncomingStation.Value = this.hfIncomingStation.Value.Trim('|');
                    this.hfOutgoingStation.Value = this.hfOutgoingStation.Value.Trim('|');
                }


            }
        
        }

        private List<VIBA_CARD> cards;
        public List<VIBA_CARD> Cards
        {
            get
            {
                if (this.cards == null)
                {
                    using (var ctx = new BTSModelDataContext())
                    {
                        this.cards = ctx.VIBA_CARDs.ToList();
                    }
                }

                return this.cards;
            }
            set { this.cards = value; }
        }

        public List<VIBA_THIET_BI> Devices
        {
            get
            {
                if (_devices == null)
                {
                    using (var ctx = new Models.BTSModelDataContext())
                        _devices = ctx.VIBA_THIET_BIs.ToList();
                }
                return _devices;
            }
            set { _devices = value; }
        }
        private List<VIBA_THIET_BI> _devices;

        public List<VIBA_TRAM> Stations
        {
            get
            {
                if (_stations == null)
                {
                    using (var ctx = new Models.BTSModelDataContext())
                        _stations = ctx.VIBA_TRAMs.ToList();
                }
                return _stations;
            }
            set { _stations = value; }
        }
        private List<VIBA_TRAM> _stations;

        public string GetCardName(int cardId)
        {
            if (cardId.ToString() == null)
                cardId = -10000000;
            var first = this.Cards.FirstOrDefault(x => x.Card_Id == cardId);
            if (first != null)
                return first.Card_TenCard;
            return string.Empty;
        }

        public int GetPortNumber(int cardId)
        {
            if (cardId == null)
                cardId = -10000000;
            var first = this.Cards.FirstOrDefault(x => x.Card_Id == cardId);
            if (first != null)
                return first.Card_SoPort.Value;
            return -1000000000;
        }

        public string GetDeviceName(string deviceId)
        {
            if (deviceId == null)
                deviceId = "";
            var first = this.Devices.FirstOrDefault(x => x.ThietBi_Id.Trim() == deviceId.Trim());
            if (first != null)
                return first.ThietBi_Ten;
            return string.Empty;
        }

        public string GetDeviceName(int cardId)
        {
            if (cardId.ToString() == null)
                cardId = -1000000;
            var firstCard = this.Cards.FirstOrDefault(x => x.Card_Id == cardId);
            if (firstCard != null)
            {
                var firstDevice = this.Devices.FirstOrDefault(x => x.ThietBi_Id.Trim() == firstCard.ThietBi_Id.ToString());
                if (firstDevice != null)
                    return firstDevice.ThietBi_Ten;
            }
            return string.Empty;
        }

        public string GetStationName(string stationId)
        {
            if (stationId == null)
                stationId = "";
            var first = this.Stations.FirstOrDefault(x => x.Tram_Id.Trim() == stationId.Trim());
            if (first != null)
                return first.Tram_Ten;
            return string.Empty;
        }

        public void NormalizeList(List<string> list)
        {
            for (int i = 0; i < list.Count; i++)
                list[i] = list[i].Trim();
        }



        public List<string> GetStationNames(List<string> stationIds)
        {
            var list = this.Stations.Where(x => stationIds.Contains(x.Tram_Id)).Select(x => x.Tram_Ten).ToList();
            return list;
        }

        private int GetSoPort(string deviceId)
        {
            if (deviceId == null)
                deviceId = "";
            var first = this.Cards.FirstOrDefault(x => x.ThietBi_Id.ToString() == deviceId.Trim());
            if (first != null)
                return first.Card_SoPort != null ? first.Card_SoPort.Value : -1;
            return -1;
        }

    }
}